package com.data.modules.message.websocket;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.data.common.base.BaseMap;
import com.data.common.constant.WebsocketConst;
import com.data.common.modules.redis.client.BootRedisClient;
import com.data.common.util.SpringContextUtils;
import com.data.modules.log.entity.WsLog;
import com.data.modules.log.service.IWsLogService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;

/**
 * @Author boot
 * @Date 2021/11/29 9:41
 * @Description: 此注解相当于设置访问URL
 */
@SuppressWarnings("ALL")
@Component
@Slf4j
@ServerEndpoint("/websocket/{userId}") //此注解相当于设置访问URL
@Data
public class WebSocket {
    private Session session;
    private String userId;

    private static final String REDIS_TOPIC_NAME = "socketHandler";

    @Resource
    private BootRedisClient bootRedisClient;

    /**
     * 缓存 webSocket连接到  单机服务class中（整体方案支持集群）
     */
    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
    public static Map<String, Session> sessionPool = new HashMap<String, Session>();


    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        try {
            this.session = session;
            this.userId = userId;
            webSockets.add(this);
            sessionPool.put(userId, session);
            log.info("onOpen=userId:{}【websocket消息】有新的连接，总数为:{}",userId, webSockets.size());
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }

    @OnClose
    public void onClose() {
        log.error("onClose=userId:{}【websocket消息】连接断开，总数为:{}",this.userId, webSockets.size());
        try {
            webSockets.remove(this);
            sessionPool.remove(this.userId);
        } catch (Exception e) {
            log.error("===onClose userId:{}",this.userId);
            log.error(e.getMessage(),e);
        }
    }


    /**
     * 服务端推送消息
     *
     * @param userId
     * @param message
     */
    public boolean pushMessage(String userId, String message) {
        Session session = sessionPool.get(userId);
        //TODO support clustor to send msg
        if(session == null || !session.isOpen()){
            log.error("pushMessage userId :{} session is null this.userId:{} try this.session :{}",userId,this.userId,this.session );
            session = this.session;
        }
        if (session != null && session.isOpen()) {
            try {
                synchronized (session){
                    log.error("【websocket消息】 userId:{} 单点消息:{}",userId, message);
                    session.getBasicRemote().sendText(message);
                    return true;
                }
            } catch (Exception e) {
                log.error(e.getMessage(),e);
                return false;
            }
        }

        return false;
    }

    /**
     * 服务器端推送消息
     */
    public void pushMessage(String message) {
        log.error("---pushMessage--{}",message);
        try {
            webSockets.forEach(ws -> ws.session.getAsyncRemote().sendText(message));
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }

    /**
     * 接受消息
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        log.error("onMessage userId:{}【websocket消息】收到客户端消息:{},this.session:{}" ,this.getUserId(),message,this.session);
        /*for (WebSocket webSocket : webSockets) {
            jumpSend(webSocket,message);
        }*/
        if(sessionPool.get(this.getUserId()) == null){
            webSockets.add(this);
            sessionPool.put(this.userId, this.session);
        }
        JSONObject obj = new JSONObject();
        obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_CHECK);
        obj.put(WebsocketConst.MSG_TXT, "心跳响应");
        if(ObjectUtil.isEmpty(message)|| "{\"type\":\"ping\"}".equals(message) || message.contains("hello")){
            if(this.getUserId().contains("_biz")){
                //仅记录一次？ 每次都记录？
                saveWsLog(message,WebsocketConst.CMD_USER);
            }
            sendJumpMessage(this.getUserId(),obj.toJSONString());
        }else {
            if(this.getUserId().contains("_log") || this.getUserId().contains("_biz")){
                saveWsLog(message,WebsocketConst.CMD_TOPIC);
            }else{
                sendJumpMessage(this.getUserId(),message);
            }

        }
    }

    private void saveWsLog(String msg,String type){
        WsLog wsLog = new WsLog();
        wsLog.setCodeLog(msg);
        wsLog.setDeviceId(this.getUserId());
        if(ObjectUtil.isNotEmpty(type)){
        }
        if(this.getUserId().contains("_biz")){
            wsLog.setDeviceStatus("biz");
        }
        if(this.getUserId().contains("_log")){
            wsLog.setDeviceStatus("log");
        }

        if (msg.contains("heartcheck")){
            wsLog.setDeviceStatus("heartcheck");
        }

        if(WebsocketConst.CMD_USER.equals(type)){
            wsLog.setDeviceDesc(msg);
            if(msg.contains("type=hello")){
                wsLog.setCodeLog("");
            }
        }
        IWsLogService wsLogService = SpringContextUtils.getBean(IWsLogService.class);
        wsLogService.save(wsLog);
    }

    private void jumpSend(WebSocket webSocket,String message) {
        JSONObject obj = new JSONObject();
        obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_CHECK);
        obj.put(WebsocketConst.MSG_TXT, "心跳响应");
        List<String> userIds = webSockets.stream().map(WebSocket::getUserId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());

        //{"type":"ping"}
        if(ObjectUtil.isEmpty(message)|| "{\"type\":\"ping\"}".equals(message)){
            //防止同一个userId 同时发送多次 心跳
            send(userIds,webSocket,obj.toJSONString());
        }else {
            send(userIds,webSocket,message);

        }
    }
    private void send(List<String> userIds, WebSocket webSocket, String msg) {
        if(userIds.contains(webSocket.getUserId())){
            userIds.remove(webSocket.getUserId());
            Session session = sessionPool.get(webSocket.getUserId());
            if(session == null || !session.isOpen()){
                log.error("send userId :{} session is null this.userId:{} try this.session :{}",userId,this.userId,this.session );
                session = this.session;
            }
            if(session == null || !session.isOpen()){
                return;
            }
            try {
                synchronized (session){
                    session.getBasicRemote().sendText(msg);
                    //webSocket.pushMessage(msg);
                }
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }
    }

    public void sendJumpMessage(String userId, String msg) {
        Session session = sessionPool.get(userId);
        // 处理 socketIM
        boolean flag = socketImMsg(userId,msg);
        if(flag){
            return ;
        }
       /* if(session == null || !session.isOpen()){
            log.error("sendJumpMessage userId :{} session is null this.userId:{} try this.session :{}",userId,this.userId,this.session );
            session = this.session;
        }*/
        if(session == null || !session.isOpen()){
            return;
        }
        try {
            synchronized (session){
                session.getBasicRemote().sendText(msg);
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }

    /**
     * 兼容处理 socketIM 消息
     * @param userId
     * @param message
     * @return
     */
    private boolean socketImMsg(String userId, String message) {
        boolean flag = false;
        String imMsg = "";
        String toUserId = "";
        if(message.contains("imMsg")){
            flag = true;
            JSONObject obj = JSONObject.parseObject(message);
            toUserId = obj.getString("toUserId");
            JSONObject tmp = obj.getJSONObject("imMsg");
            imMsg = tmp.toString();
        }else{
            toUserId = userId;
        }

        if(toUserId == null){
            toUserId = userId;
            //应该直接返回
        }
        log.info("socketImMsg toUserId:{}",toUserId);
        Session session = sessionPool.get(toUserId);

        if(flag){
            if(session == null || !session.isOpen()){
                // session 为空 说明 不在此服务或已经下线
                log.error("socketImMsg userId :{} session is null this.userId:{} try toUserId :{}",userId,this.userId,toUserId );
            }
            try {
                synchronized (session){
                    session.getBasicRemote().sendText(imMsg);
                }
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }

        }

        return flag;
    }

    /**
     * 后台发送消息到redis
     *
     * @param message
     */
    public void sendMessage(String message) {
        log.error("【websocket消息】广播消息:{}", message);
        BaseMap baseMap = new BaseMap();
        baseMap.put("userId", "");
        baseMap.put("message", message);
        bootRedisClient.sendMessage(REDIS_TOPIC_NAME, baseMap);
    }

    /**
     * 此为单点消息
     *
     * @param userId
     * @param message
     */
    public void sendMessage(String userId, String message) {
        BaseMap baseMap = new BaseMap();
        baseMap.put("userId", userId);
        baseMap.put("message", message);
        bootRedisClient.sendMessage(REDIS_TOPIC_NAME, baseMap);
    }

    /**
     * 此为单点消息(多人)
     *
     * @param userIds
     * @param message
     */
    public void sendMessage(String[] userIds, String message) {
        for (String userId : userIds) {
            sendMessage(userId, message);
        }
    }

}
